package jk.fox.common;

import java.net.InetSocketAddress;
import java.net.URI;

/**
 * @Auther cuichao
 * @Description: RpcURIUtils
 * @Date: create in 2020/4/18 15:15
 */
public class RpcURIUtils {


    public static URI getUri(String scheme, String address, String path){
        StringBuilder builder = new StringBuilder();
        builder.append(scheme).append("://").append(address).append("/").append(path);
        URI uri = URI.create(builder.toString());
        return uri;
    }

    public static URI getUri(String address, String path){
        return getUri(RpcDict.DEFAULT_SCHEMA, address,path);
    }


    public static URI getUri(String host,int port, String path){
        return getUri(RpcDict.DEFAULT_SCHEMA,host,port,path);
    }


    public static URI getUri(String scheme, String host,int port, String path){
        StringBuilder builder = new StringBuilder();
        builder.append(scheme).append("://").append(host).append(":").append(port).append("/").append(path);
        URI uri = URI.create(builder.toString());
        return uri;
    }


    public static String getHost(URI uri){
        return uri.getHost();
    }


    public static int getPort(URI uri){
        return uri.getPort();
    }

    public static String getPath(URI uri){
        String path = uri.getPath();
        if(path.indexOf("/") == 0){
            path=path.substring(1);
        }
        return path;
    }


    public static String[] getDomainAndPath(URI uri){
        String path = getPath(uri);
        String[] split = path.split("/");
        return split;
    }

    public static String[] getDomainAndPath(String path){
        String[] split = path.split("/");
        return split;
    }


    public static String getAddress(InetSocketAddress address){
        String host = address.getHostString();
        int port = address.getPort();
        return host+":"+port;
    }

    public static String getAddress(URI uri){
        String host = getHost(uri);
        int port = getPort(uri);
        return host+":"+port;
    }

    public static String getAddress(String scheme,String hostname, int port){
        return scheme+"://"+hostname+":"+port;
    }

    public static InetSocketAddress getInetSocketAddress(URI uri){
        return new InetSocketAddress(uri.getHost(), uri.getPort());
    }


}
